﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using NHibernate;
using DunSilverlight.Web.Comm;
using DunLibrary.User;
using DunSilverlight.Web.Serializable;
using System.ServiceModel.Activation;

namespace DunSilverlight.Web.UserWcf
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“RightService”。
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class RightService : BaseService<Right>, IRightService
    {

        
        /// <summary>
        /// 通过用户id获得一个权限列表  
        /// 这个用
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public string GetRightsByRoleId(int roleId)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                try
                {
                    DunLibrary.User.Role r = sess.CreateQuery("from Role where Id=:id").SetParameter<int>("id", roleId).UniqueResult<Role>();

                    if (r != null)
                    {
                        string json = JsonSerializerHelper.EntityToJson(r.Rights);
                        return PackJsonListResult("true", json, string.Empty,r.Rights.Count);
                    }
                    else
                    {
                        return this.PackJsonListResult("false", "[]", "角色不存在!",0);
                    }
                }
                catch (Exception ex)
                {
                    return this.PackJsonListResult("false", "[]", ex.Message,0);
                }

            }
        }

        /// <summary>
        /// 因为要删除关系，所以需要重写
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override string DeleteById(int id)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                ITransaction tx = sess.BeginTransaction();
                try
                {
                    Right entity = sess.Load<Right>(id);
                    sess.Delete(entity);
                    sess.CreateSQLQuery("delete from User_Role_Right where RightId = " + id + "").UniqueResult();
                    sess.Flush();
                    tx.Commit();
                    return PackJsonResult("true", "true", string.Empty);
                }
                catch (Exception ex)
                {
                    tx.Rollback();
                    return PackJsonResult("false", "false", ex.Message);
                }
            }
        }
    }
}
